package com.unfind.myahmt.xyb.network

import com.google.gson.Gson
import com.xb.sourest.base.IModel
import com.xb.sourest.utils.RsaHelper
import io.reactivex.Flowable
import io.reactivex.FlowableTransformer
import io.reactivex.ObservableTransformer
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.functions.Function
import io.reactivex.schedulers.Schedulers
import okhttp3.MediaType
import okhttp3.MultipartBody
import okhttp3.RequestBody
import org.reactivestreams.Publisher
import java.io.File

/**
 * 作用：线程调度
 * 作者：unfind
 * 时间：2019年05月09日17:30:33
 */
object NetworkScheduler {
    fun <T> compose(): ObservableTransformer<T, T> {
        return ObservableTransformer { observable ->
            observable.subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread())
        }
    }


    /**
     * 线程切换
     *
     * @return
     */
    fun <T : IModel> getScheduler(): FlowableTransformer<T, T> {
        return FlowableTransformer { upstream ->
            upstream.subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
        }
    }

    /**
     *  POST
     * @param params
     * @return
     */
     fun setRequestBody(params: Map<String, Any?>): RequestBody {
        val new_Params = params.toMutableMap()
        return RequestBody.create(MediaType.parse("application/json; charset=utf-8"), RsaHelper.rsaEncode(Gson().toJson(new_Params)))
    }

    /**
     * 图片上传参数
     * @param params
     * @return
     */
    fun setImageRequestBody(params: List<File>,key:String): MutableList<MultipartBody.Part> {
        var parts = mutableListOf<MultipartBody.Part>()
        for (file in params) {
            var requestBody = RequestBody.create(MediaType.parse("multipart/form-data"), file)
            var part = MultipartBody.Part.createFormData(key, file.name, requestBody)
            parts.add(part)
        }
        return  parts
    }

}